package LocalCRM::Doc::VAct;

use base 'LocalCRM::Doc';
use Class::Date;
use PDF::Table;
use strict;

sub new
{
    my $self= shift->SUPER::new();
    my %arg = @_;
    my ($x,$y);
    my @r;

    $self->{data}->{content}=
    [
	[
	    $self->utf2win('Дата'),
	    $self->utf2win('Документ'),
	    $self->utf2win('Дебет'),
	    $self->utf2win('Кредит'),
	    $self->utf2win('Дата'),
	    $self->utf2win('Документ'),
	    $self->utf2win('Дебет'),
	    $self->utf2win('Кредит'),
	],
    ];

    $self->{_table} = new PDF::Table;

    $self->{page} = $self->{pdf}->page();
    $self->{page}->mediabox(842.4,597.6);

    my $text = $self->{page}->text();

    $self->{_id} = $arg{id};

    $self->id();

    $text->font($self->{font}->{VerdanaB},10);
    $text->translate(360,550);
    $text->text($self->utf2win('Акт сверки'));

    $text->font($self->{font}->{Verdana},10);
    $self->{_table}->text_block
    (
	$text,
	$self->utf2win(sprintf 'взаимных расчетов за период с %s по %s.', $self->{v_act}->{period_start}->strftime('%d.%m.%Y'),$self->{v_act}->{period_stop}->strftime('%d.%m.%Y')),
	x	=> 120,
	y	=> 535,
	w	=> 540,
	h	=> 20,
	align	=> 'center',
    );

    $self->{_table}->text_block
    (
	$text,
	$self->utf2win(sprintf 'между %s и %s',$self->{v_act}->{invoice_text2},$self->{v_act}->{customer_name}),
	x	=> 120,
	y	=> 520,
	w	=> 540,
	h	=> 20,
	align	=> 'center',
    );

    $self->{_table}->text_block
    (
	$text,
	$self->utf2win(sprintf $self->{v_act}->{verification_act_title},$self->{v_act}->{invoice_text2},$self->{v_act}->{acoount_boss},$self->{v_act}->{customer_name}),
	x	=> 120,
	y	=> 470,
	w	=> 540,
	h	=> 60,
	align	=> 'center',
    );

    my ($x,$y) = $text->textpos();

    @r = $self->{_table}->table
    (
	$self->{pdf},
	$self->{page},
	$self->{data}->{content},
	x	=> 20,
	w	=> 28/2.54*72,
	start_y	=> $y-45,
	start_h	=> 200,
	font	=> $self->{font}->{Verdana},
	font_size	=> 8,
	padding	=> 3,
	column_props	=>
	[
	    {max_w=>70},
	    {min_w=>200},
	    undef,
	    undef,
	    {max_w=>70},
	    {min_w=>200},
	    undef,
	    undef,
	]
    );

# Рисуем шапку к таблице
    my $gfx = $self->{page}->gfx();

    $gfx->move($r[3][0],$y-45);
    $gfx->vline($y-15);
    $gfx->move($r[3][4],$y-45);
    $gfx->vline($y-15);
    $gfx->move($r[3][8],$y-45);
    $gfx->vline($y-15);

    $gfx->move($r[3][0],$y-15);
    $gfx->hline($r[3][8]);

    $gfx->stroke();

# Заполняем шапку
    $self->{_table}->text_block
    (
	$text,
	$self->utf2win(sprintf 'По данным %s', $self->{v_act}->{invoice_text2}),
	x	=> $r[3][0]+5,
	y	=> $y-25,
	w	=> $r[3][4]-$r[3][0]-10,
	h	=> 20,
	align	=> 'left',
    );

    $self->{_table}->text_block
    (
	$text,
	$self->utf2win(sprintf 'По данным %s', $self->{v_act}->{customer_name}),
	x	=> $r[3][4]+5,
	y	=> $y-25,
	w	=> $r[3][8]-$r[3][4]-10,
	h	=> 20,
	align	=> 'left',
    );

# Строим таблицу
#

# Рисуем подвал таблицы
    $gfx->move($r[3][0],$r[2]);
    $gfx->vline($r[2]-30);
    $gfx->move($r[3][2],$r[2]);
    $gfx->vline($r[2]-30);
    $gfx->move($r[3][3],$r[2]);
    $gfx->vline($r[2]-30);
    $gfx->move($r[3][4],$r[2]);
    $gfx->vline($r[2]-30);

    $gfx->move($r[3][6],$r[2]);
    $gfx->vline($r[2]-30);
    $gfx->move($r[3][7],$r[2]);
    $gfx->vline($r[2]-30);
    $gfx->move($r[3][8],$r[2]);
    $gfx->vline($r[2]-30);

    $gfx->move($r[3][0],$r[2]-15);
    $gfx->hline($r[3][8]);
    $gfx->move($r[3][0],$r[2]-30);
    $gfx->hline($r[3][8]);

    $gfx->stroke();

    $text->font($self->{font}->{VerdanaB},8);
    $self->{_table}->text_block
    (
	$text,
	$self->utf2win('Обороты за период'),
	x	=> $r[3][0]+5,
	y	=> $r[2]-10,
	w	=> $r[3][4]-$r[3][0]-10,
	h	=> 20,
	align	=> 'left',
    );

    $self->{_table}->text_block
    (
	$text,
	$self->utf2win('Сальдо конечное'),
	x	=> $r[3][0]+5,
	y	=> $r[2]-25,
	w	=> $r[3][4]-$r[3][0]-10,
	h	=> 20,
	align	=> 'left',
    );

    $self->{_table}->text_block
    (
	$text,
	$self->utf2win('Обороты за период'),
	x	=> $r[3][4]+5,
	y	=> $r[2]-10,
	w	=> $r[3][4]-$r[3][0]-10,
	h	=> 20,
	align	=> 'left',
    );

    $self->{_table}->text_block
    (
	$text,
	$self->utf2win('Сальдо конечное'),
	x	=> $r[3][4]+5,
	y	=> $r[2]-25,
	w	=> $r[3][4]-$r[3][0]-10,
	h	=> 20,
	align	=> 'left',
    );

    $text->font($self->{font}->{Verdana},8);

    $text->translate($r[3][2]+5,$r[2]-10);
    $text->text($self->{v_act}->{turnover_debet});

    $text->translate($r[3][3]+5,$r[2]-10);
    $text->text($self->{v_act}->{turnover_credit});

    $text->translate((($self->{v_act}->{saldo}>0)?$r[3][3]:$r[3][3])+5,$r[2]-25);
    $text->text(sprintf '%0.2f', abs($self->{v_act}->{saldo}));

    $text->translate(40,$r[2]-60);
    $text->text($self->utf2win(sprintf 'По данным %s на %s', $self->{v_act}->{invoice_text2},$self->{v_act}->{period_stop}->strftime('%d.%m.%Y')));

    $text->font($self->{font}->{VerdanaB},8);
    $text->cr(-10);
    $text->text($self->utf2win(sprintf 'задолженность в пользу %s %0.2f руб.', ($self->{v_act}->{saldo}>0)?$self->{v_act}->{customer_name}:$self->{v_act}->{invoice_text2},abs($self->{v_act}->{saldo})));

    $text->font($self->{font}->{Verdana},8);

    $text->cr(-20);
    $text->text($self->utf2win(sprintf('От %s', $self->{v_act}->{invoice_text2})));

    $text->cr(-20);
    $text->text('________________________________');

    $text->cr(-20);
    $text->text($self->utf2win(sprintf('________________________________ (%s)',$self->{v_act}->{acoount_boss})));

    $text->distance(500,40);
    $text->text($self->utf2win(sprintf('От %s', $self->{v_act}->{customer_name})));

    $text->cr(-20);
    $text->text('________________________________');

    $text->cr(-20);
    $text->text('________________________________(__________________)');

    return $self;
}

sub id
{
#    my $self = shift->SUPER::id($_[0]);
    my $self = shift;
    my $dbh = $self->{_db}->{_db};

    my $query = 'SELECT '
		    .'`va`.*,'
		    .'(`va`.`turnover_debet`-`va`.`turnover_credit`) AS `saldo`,'
		    .'`e`.`invoice_text2`,'
		    .'`e`.`verification_act_title`,'
		    .'`e`.`acoount_boss`,'
		    .'`cs`.`customer_name`,'
		    .'`ct`.`contract_number`,'
		    .'`ct`.`account_id`'
		.' FROM `verification_act` va'
		.' JOIN `contract` ct ON `ct`.`id`=`va`.`contract_id`'
		.' JOIN `customer` cs ON `cs`.`account_id`=`ct`.`account_id`'
		.' JOIN `executive` e ON `e`.`id`=`ct`.`executive_id`'
		.' WHERE `va`.`id`=?';

    my $sth = $dbh->prepare($query);

    if ( $sth->execute($self->{_id}) )
    {
	if ( $self->{v_act} = $sth->fetchrow_hashref() )
	{
	    foreach my $key ( keys %{$self->{v_act}} )
	    {
		$self->{v_act}->{$key} =~ s/\\//g;
	    }

	    my $sth = $dbh->prepare('SELECT `va`.*,`i`.`date` AS `idate`,`p`.`date` AS `pdate` FROM `verification_act_item` va LEFT JOIN `payment` p ON `p`.`id`=`va`.`payment_id` LEFT JOIN `invoice` i ON `i`.`id`=`va`.`invoice_id` WHERE `va`.`verification_act_id`=?');

	    if ( $sth->execute($self->{v_act}->{id}) )
	    {
		while ( my $row = $sth->fetchrow_hashref() )
		{
		    $row->{date} = Class::Date->new($row->{idate}||$row->{pdate});

		    if ( $row->{payment_id} )
		    {
			push @{$self->{data}->{content}},
			[
			    $row->{date}->strftime('%d.%m.%Y'),
			    $row->{payment_id},
			    undef,
			    $row->{sum},
			    '',
			    '',
			    '',
			    '',
			];
		    }
		    elsif ( $row->{invoice_id} )
		    {
			push @{$self->{data}->{content}},
			[
			    $row->{date}->strftime('%d.%m.%Y'),
			    $row->{invoice_id},
			    $row->{sum},
			    undef,
			    '',
			    '',
			    '',
			    '',
			];
		    }
		}
	    }
	}

	if ( $self->{v_act}->{period_start} ) { $self->{v_act}->{period_start} = Class::Date->new($self->{v_act}->{period_start}); }
	if ( $self->{v_act}->{period_stop} ) { $self->{v_act}->{period_stop} = Class::Date->new($self->{v_act}->{period_stop}); }
    }

    return $self;
}

sub filename
{
    my $self = shift;
    my $ext  = $_[0]||'pdf';
    my ($class) = (ref $self) =~ /localcrm::doc::(.+)/i;

    if ( $class )
    {
	my $contract = $self->{v_act}->{contract_number};
	$contract =~ s/[^\w\d]/\_/g;

	return sprintf '%s_%d_%s.%s', $contract, $self->{_id}, lc($class), $ext;
    }
}

sub save
{
    my $self = shift;

    if ( $self->{_id} )
    {
	if ( my $filename = $self->filename() )
	{
	    unless ( -d(sprintf '%s/%04d',$self->{_cfg}->val('Path','files'), $self->{v_act}->{account_id}) ) { mkdir(sprintf '%s/%04d',$self->{_cfg}->val('Path','files'), $self->{v_act}->{account_id}); }
	    unless ( -d(sprintf '%s/%04d/verification_acts',$self->{_cfg}->val('Path','files'), $self->{v_act}->{account_id}) ) { mkdir(sprintf '%s/%04d/verification_acts',$self->{_cfg}->val('Path','files'), $self->{v_act}->{account_id}); }

	    $self->{pdf}->saveas( sprintf '%s/%04d/verification_acts/%s', $self->{_cfg}->val('Path','files'), $self->{v_act}->{account_id}, $filename );

	    return $filename;
	}
    }
}

1;
